import { Sequelize } from 'sequelize';
import mysql from 'mysql2/promise';
import config from '../config';

const { database } = config;

// 创建MySQL连接池
const pool = mysql.createPool({
  host: database.host,
  port: database.port,
  database: database.name,
  user: database.user,
  password: database.password,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 创建Sequelize实例
const sequelize = new Sequelize({
  host: database.host,
  port: database.port,
  database: database.name,
  username: database.user,
  password: database.password,
  dialect: 'mysql',
  logging: config.nodeEnv === 'development' ? console.log : false,
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  define: {
    timestamps: true,
    underscored: true,
    freezeTableName: true
  }
});

/**
 * 测试数据库连接
 */
export const testConnection = async (): Promise<void> => {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功！');
  } catch (error) {
    console.error('数据库连接失败:', error);
    throw error;
  }
};

/**
 * 同步数据库模型
 */
export const syncDatabase = async (): Promise<void> => {
  try {
    await sequelize.sync({ alter: true });
    console.log('数据库模型同步成功！');
  } catch (error) {
    console.error('数据库模型同步失败:', error);
    throw error;
  }
};

// 导出连接池和Sequelize实例
export { pool };
export default sequelize;